<template>
  <!-- <template> -->
  <a-config-provider prefix-cls="ss">
    <div class="container">
      <!-- 创意混剪项目头部 -->
      <navBack
        :leftConfig="{
          isShow: true,
        }"
        :contentConfig="{
          isShow: false,
        }"
        :rightConfig="{
          isShow: true,
        }"
        @backClick="backClick"
      >
        <!-- 头部左侧文字 -->

        <template #left_text>
          <span style="font-size: 16px; margin-left: 15px; font-weight: 400"
            >脚本广场</span
          >
        </template>

        <template #right_btns>
          <div class="right_btns">
            <a-button @click="handleSaveScript('mixcut')">导入剪辑</a-button>
            <a-button
              style="font-size: 13px; border-radius: 5px; margin: 0 10px"
              type="primary"
              @click="handleSaveScriptCopy('save')"
              >创建副本</a-button
            >
            <a-button
              style="font-size: 13px; border-radius: 5px"
              type="primary"
              :disabled="false"
              @click="handleSaveScript('save')"
              >完成脚本</a-button
            >
          </div>
        </template>
      </navBack>
      <div class="content-page">
        <!-- 名称输入框 -->
        <div class="top-ipt">
          <div class="ipt">
            <a-input
              placeholder="请输入脚本名称"
              v-model:value="initData.title"
              :bordered="false"
              style="font-size: 30px; font-weight: 500"
            ></a-input>
          </div>
        </div>
        <!-- 列表 -->
        <a-table
          :columns="columns"
          :data-source="initData.script_scenes"
          bordered
          :pagination="false"
          :scroll="{ x: 1200 }"
        >
          <!-- 列表头部 -->
          <template #headerCell="{ column }">
            <!-- 台词文案 -->
            <template v-if="column.key === 'line_audio'">
              <div class="th_line_audio">
                <span>{{ column.title }}</span>
                <a-space>
                  <span>
                    <a-button
                      size="small"
                      :disabled="!isAIcanClick"
                      :loading="iconLoading"
                      @click="AIWritingAssistantHandle"
                      style="display: flex; align-items: center"
                    >
                      <template #icon>
                        <cu-icon
                          type="icon-AIxiezuozhushou"
                          style="
                            color: #2580fd;
                            font-size: 18px;
                            margin-top: 3px;
                          "
                        ></cu-icon>
                      </template>
                      AI写作助手
                    </a-button>
                  </span>
                  <span>
                    <a-tooltip>
                      <template #title
                        >点击【风险词检测】对脚本中话术进行风险词检测
                        <div>
                          1、检查到风险词，违禁词采用高亮的形式显示在对应的某一句话中
                        </div>
                        <div>2、风险词包含官方风险词与自定义风险词</div>
                      </template>
                      <QuestionCircleOutlined style="margin-right: 4px" />
                    </a-tooltip>
                    <a-button
                      :disabled="!isAIcanClick"
                      type="default"
                      size="small"
                      @click="riskWordDetnHandle(initData)"
                      >风险词检测</a-button
                    >
                  </span>
                  <span>
                    <a-tooltip>
                      <template #title
                        >点击总的「台词配音」，将按照配置的音色内容对脚本中所有台词文案进行配音覆盖</template
                      >
                      <QuestionCircleOutlined style="margin-right: 4px" />
                    </a-tooltip>
                    <a-button
                      :disabled="!isAIcanClick"
                      type="default"
                      size="small"
                      @click="globalAudioHandle(initData.audio_config, index)"
                      >台词配音</a-button
                    >
                  </span>
                </a-space>
              </div>
            </template>
          </template>
          <!-- 列表主体部分 -->
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.key === 'id'">
              {{ index }}
            </template>
            <template v-if="column.key === 'actions'">
              <div style="display: flex; justify-content: center">
                <div class="delet-btn">
                  <a-popover placement="topLeft" trigger="click">
                    <template #content>
                      <div style="cursor: pointer">
                        <a-popover placement="topLeft">
                          <template #content>
                            <span>向上添加一行</span>
                          </template>
                          <p @click="addLineTopHandle(index)">
                            <cu-icon
                              type="icon-svg-right-top"
                              style="font-size: 20px"
                            ></cu-icon>
                          </p>
                        </a-popover>

                        <a-popover placement="topLeft">
                          <template #content>
                            <span>删除行</span>
                          </template>
                          <p @click="deleteLineHandle(index)">
                            <cu-icon
                              type="icon-shanchu"
                              style="font-size: 15px"
                            ></cu-icon>
                          </p>
                        </a-popover>
                        <a-popover placement="topLeft">
                          <template #content>
                            <span>清空内容</span>
                          </template>
                          <p @click="deleteContentHandle(index)">
                            <delete-outlined style="font-size: 15px" />
                          </p>
                        </a-popover>
                        <a-popover placement="topLeft">
                          <template #content>
                            <span>向下添加一行</span>
                          </template>
                          <p @click="addLineBottomHandle(index)">
                            <cu-icon
                              type="icon-youxiajiantou"
                              style="font-size: 20px"
                            ></cu-icon>
                          </p>
                        </a-popover>
                      </div>
                    </template>
                    <HolderOutlined />
                  </a-popover>
                </div>
              </div>
            </template>
            <!-- {{ record }} -->
            <!-- 分镜名称 -->
            <template v-if="column.key === 'name'">
              <div class="td_storyboard_name">
                <a-textarea
                  style="height: 100%; width: 100%"
                  placeholder="请输入分镜名称"
                  :bordered="false"
                  :maxlength="20"
                  class="no-resize textarea"
                  v-model:value="initData.script_scenes[index].name"
                />
                <div class="font-count">
                  {{ initData.script_scenes[index].name.trim().length }}/20
                </div>
              </div>
            </template>
            <!-- 分镜描述 -->
            <template v-if="column.key === 'remark'">
              <div class="td_storyboard_desc">
                <!-- 左侧分镜描述文本 -->
                <div class="td_storyboard_descLf">
                  <a-textarea
                    style="height: 100%; width: 100%"
                    placeholder="详细描述分镜"
                    :bordered="false"
                    class="no-resize textarea"
                    :maxlength="100"
                    v-model:value="initData.script_scenes[index].remark"
                  />
                  <div class="font-count">
                    {{ initData.script_scenes[index].remark.trim().length }}/100
                  </div>
                </div>
                <!-- 右侧分镜描述文件上传 -->
                <div class="file-upload-img">
                  <!-- 有图片情况下 -->
                  <div
                    class="file-img"
                    v-if="
                      initData.script_scenes[index].remark_example_url.length >
                      0
                    "
                  >
                    <a-popover
                      placement="topLeft"
                      :overlayStyle="{ zIndex: '1000' }"
                    >
                      <template #content>
                        <!-- 溢出分镜文本图片显示组件 -->
                        <TemplateVideoList
                          :urlList="
                            initData.script_scenes[index].remark_example_url
                          "
                          :parentIndex="index"
                          :updateType="'remark_example_url'"
                          @deleteParentUrl="deleteParentUrl"
                          @updateParentsUrl="updateParentsUrl"
                        />
                      </template>
                      <!-- 分镜描述展示图片 -->
                      <img
                        v-if="
                          initData.script_scenes[index].remark_example_url[0]
                            ?.scene_type == 'image'
                        "
                        style="height: 180px; width: 140px; object-fit: cover"
                        :src="
                          initData.script_scenes[index].remark_example_url[0]
                            ?.material_url
                        "
                      />
                      <!-- 分镜描述视频展示 -->
                      <video
                        v-else
                        style="height: 180px; width: 140px"
                        :src="
                          initData.script_scenes[index].remark_example_url[0]
                            ?.material_url
                        "
                      ></video>
                      <span class="img-count">{{
                        initData.script_scenes[index].remark_example_url
                          ?.length || ""
                      }}</span>
                    </a-popover>
                  </div>
                  <!-- 图片上传 -->
                  <div
                    class="upload-img"
                    @click="importImg(index, 'remark')"
                    v-else
                  >
                    <div style="font-size: 24px; font-weight: 600">+</div>
                    <div>添加素材</div>
                  </div>
                </div>
              </div>
            </template>
            <!-- 台词文案 -->
            <template v-if="column.key === 'line_audio'">
              <div class="td_line_audio">
                <div class="line_dubbing-textarea">
                  <a-textarea
                    style="width: 100%; height: 140px"
                    placeholder="输入脚本台词，回车换行"
                    class="no-resize textarea"
                    :bordered="false"
                    v-model:value="
                      initData.script_scenes[index].line_audio[0].elements[0][0]
                        .text
                    "
                    :disabled="itemSpinning[index] || !isAIcanClick"
                    @blur="lineAudioBlurHandle(index)"
                    @change="lineAudioChangeHandle(index)"
                  />
                </div>
                <!-- 无音频播放地址 -->
                <div
                  class="line_dubbing"
                  v-if="!initData.script_scenes[index]?.line_audio[0].audio_url"
                >
                  <a-spin
                    tip="音频加载中"
                    :spinning="
                      lineDubbingLoading.length && lineDubbingLoading[index]
                    "
                  >
                    <span
                      class="line_dubbing_btn"
                      :style="{
                        cursor: !isAIcanClick ? 'not-allowed' : '',
                        background: !isAIcanClick ? '#f5f5f5' : '',
                      }"
                      @click="
                        isAIcanClick
                          ? lineAudioHandle(
                              initData.script_scenes[index],
                              index
                            )
                          : ''
                      "
                    >
                      <cu-icon
                        type="icon-quanjuzimupeiyin"
                        style="
                          color: #7794ca;
                          height: 100%;
                          margin-right: 3px;
                          font-size: 20px;
                        "
                      ></cu-icon
                      >台词配音
                    </span>
                  </a-spin>
                  <!-- 素材库导入 -->
                  <a-button
                    type="link"
                    class="import_material"
                    :disabled="lineDubbingLoading[index] || !isAIcanClick"
                    @click="openCopyLibraryModal(index)"
                    >文案库导入</a-button
                  >
                </div>

                <!-- 有音频播放地址 -->
                <div class="hasurl_line_dubbing" v-else>
                  <div
                    class="line_dubbing_btn"
                    :style="{
                      cursor: !isAIcanClick ? 'not-allowed' : '',
                      background: !isAIcanClick ? '#f5f5f5' : '',
                    }"
                    @click="
                      isAIcanClick
                        ? lineAudioHandle(initData.script_scenes[index], index)
                        : ''
                    "
                  >
                    <span>
                      <cu-icon
                        class="icon"
                        type="icon-shengkongqiehuan"
                        style="margin-right: 5px; color: #87a6d4"
                      />
                      台词配音</span
                    >

                    <!-- 音频时长 -->
                    <span style="margin: 0 5px">{{
                      record.line_audio[0].duration_text
                    }}</span>

                    <!-- 播放按钮 -->
                    <a-spin
                      size="small"
                      :spinning="itemSpinning && itemSpinning[index]"
                    >
                      <span
                        class="play"
                        v-if="itemPlaying[index]"
                        @click.stop="
                          isAIcanClick ? pauseAudio(record, index) : ''
                        "
                      >
                        暂停
                        <StopOutlined
                          style="color: #87a6d4; margin-right: 3px"
                        />
                      </span>

                      <!-- 暂停按钮 -->
                      <span
                        class="pause"
                        v-else
                        @click.stop="
                          isAIcanClick ? playAudio(record, index) : ''
                        "
                        >试听<caret-right-outlined style="color: #87a6d4"
                      /></span>
                    </a-spin>
                  </div>
                  <!-- 音频播放器 -->
                  <audio
                    @ended="endAudioPlay(record, index)"
                    ref="audioRef"
                    :id="`audio-${record.id}`"
                    :src="
                      initData.script_scenes[index]?.line_audio[0].audio_url
                    "
                    style="display: none"
                  ></audio>
                  <!-- 素材库导入 -->
                  <a-button
                    class="import_material"
                    type="link"
                    :disabled="lineDubbingLoading[index] || !isAIcanClick"
                    @click="openCopyLibraryModal(index)"
                    >文案库导入</a-button
                  >
                </div>
              </div>
            </template>
            <!-- 已拍摄片段 -->
            <template v-if="column.key === 'example_url'">
              <!-- {{ record }} -->
              <div class="file-upload-img">
                <!-- 有图片情况下 -->
                <div
                  class="file-img"
                  v-if="initData.script_scenes[index].example_url?.length > 0"
                >
                  <a-popover
                    placement="topLeft"
                    :overlayStyle="{ zIndex: '1000' }"
                  >
                    <template #content>
                      <TemplateVideoList
                        :urlList="initData.script_scenes[index].example_url"
                        :updateType="'example_url'"
                        :parentIndex="index"
                        @deleteParentUrl="deleteParentUrl"
                        @updateParentsUrl="updateParentsUrl"
                      />
                    </template>
                    <!-- 展示图片 -->
                    <img
                      v-if="
                        initData.script_scenes[index].example_url[0]
                          ?.scene_type == 'image'
                      "
                      style="height: 180px; width: 140px; object-fit: cover"
                      :src="
                        initData.script_scenes[index].example_url[0]
                          ?.material_url
                      "
                    />
                    <!-- 视频展示 -->
                    <video
                      v-else
                      style="height: 180px; width: 140px"
                      :src="
                        initData.script_scenes[index].example_url[0]
                          ?.material_url
                      "
                    ></video>
                    <span class="img-count">{{
                      initData.script_scenes[index].example_url.length || ""
                    }}</span>
                  </a-popover>
                </div>
                <!-- 图片上传 -->

                <div
                  class="upload-img"
                  @click="importImg(index, 'example_url')"
                  v-else
                >
                  <div style="font-size: 24px; font-weight: 600">+</div>
                  <div>添加素材</div>
                </div>
              </div>
            </template>
          </template>
        </a-table>
        <!-- 添加一行 -->
        <div class="addLine" @click="addHandle">
          <span
            >+添加一行 <i class="triangle_left"></i>
            <i class="triangle_right"></i
          ></span>
        </div>
      </div>
    </div>

    <!-- 单个配音设置弹窗组件 -->
    <LineDubbing
      @deleteLineAudio="deleteLineAudio"
      ref="lineDubbing"
      @closeDubbing="closeDubbing"
    />
    <!-- 全局配音设置弹窗组件 -->
    <globallineDubbing
      ref="globalLineDub"
      @closeglobalDubbing="closeglobalDubbing"
    />
    <!-- 素材库组件 -->
    <ChooseMaterial
      :isClip="false"
      :material_type="openMaterialModalType"
      :multiple="openMaterialModalType == 'image_video'"
      :visible="materiallibraryShow"
      @close="
        openMaterialModalType == 'image_video'
          ? closeChooseMaterial($event, 'material_type')
          : audioLItemImportSuccess($event)
      "
    />
    <!-- 文案库 -->
    <CopyLibraryModal
      ref="copyLibraryModal"
      @importSuccess="audioLItemImportSuccess"
    />
    <!--风险词检测组件 -->
    <RiskWordDetection ref="riskWordDetection" />
    <AIWritingAssistant
      ref="AIWritingAssistantRef"
      @emitArr="emitArr"
    ></AIWritingAssistant>
  </a-config-provider>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  ref,
  computed,
  nextTick,
  createVNode,
  onMounted,
  watch,
} from "vue";
import { useRouter, useRoute } from "vue-router";
// 头部组件
import navBack from "../components/navBack.vue";
import request from "@/common/utils/request";
import {
  QuestionCircleOutlined,
  PlusOutlined,
  PicLeftOutlined,
  CaretRightOutlined,
  FullscreenOutlined,
  DeleteOutlined,
  StopOutlined,
  EditOutlined,
  HolderOutlined,
} from "@ant-design/icons-vue";
//单个台词配音组件
import LineDubbing from "../../CreationCenter/modules/lineDubbing.vue";
// 全局台词配音组件
import globallineDubbing from "../../CreationCenter/modules/globallineDubbing.vue";
// 文件左侧展示组件
import TemplateVideoList from "../../CreationCenter/components/templateVideoList.vue";
import { message } from "ant-design-vue";
// 拖拽组件
import Draggable from "vuedraggable";
// 文件选择弹窗组件
import ChooseMaterial from "@/views/shotstack/EditingCenter/modules/bottomSet/components/chooseMaterial.vue";
import {
  createScriptData,
  baseScriptScenesItem,
} from "../utools/baseScriptData.js";
// 随机生成id方法函数
import { nanoid } from "nanoid";
// 风险词检测组件
import RiskWordDetection from "./components/riskWordDetecDrawer.vue";
// ai写作助手
import AIWritingAssistant from "@/views/shotstack/MuseMixedCut/mixedCutCreat/components/AIWritingAssistant.vue";
import store from "@/store";
import { splitTextAndRemoveCommas } from "@/views/shotstack/MuseMixedCut/utools/index.js";
// 文案库组件
import CopyLibraryModal from "@/components/AddTextModal/CopyLibraryModal.vue";
export default defineComponent({
  name: "ScriptSquare",
  components: {
    QuestionCircleOutlined,
    PicLeftOutlined,
    FullscreenOutlined,
    DeleteOutlined,
    CaretRightOutlined,
    StopOutlined,
    // templateImgMaskModal,
    navBack,
    LineDubbing,
    globallineDubbing,
    TemplateVideoList,
    EditOutlined,
    Draggable,
    PlusOutlined,
    ChooseMaterial,
    HolderOutlined,
    RiskWordDetection,
    AIWritingAssistant,
    CopyLibraryModal,
  },
  setup() {
    const router = useRouter();
    const route = useRoute();
    const state = reactive({
      columns: [
        {
          title: "",
          dataIndex: "actions",
          key: "actions",
          align: "center",
          width: 40,
        },
        {
          title: "序号",
          dataIndex: "id",
          key: "id",
          align: "center",
          width: 40,
        },
        {
          title: "分镜名称",
          dataIndex: "name",
          key: "name",
          align: "center",
          width: 100,
        },
        {
          title: "分镜描述",
          dataIndex: "remark",
          key: "remark",
          align: "center",
          width: 200,
        },
        {
          title: "台词文案",
          dataIndex: "line_audio",
          key: "line_audio",
          align: "center",
          width: 240,
        },
        {
          title: "已拍摄片段",
          dataIndex: "example_url",
          key: "example_url",
          align: "center",
          width: 180,
        },
      ],
      visible: false, //控制弹窗显示隐藏
      materiallibraryShow: false, //控制老系统素材库弹窗显示隐藏
      parentIndex: null, //当前点击的列表父级索引
      uploadType: "", //选则图片上传的类型(remark:分镜描述，example_url：已拍摄片段)
      initData: {}, //总数据
      itemPlaying: [], // 每一项的播放状态
      itemSpinning: [], //每一项的加载状态
      lineDubbingLoading: [], //每一项无地址时候加载状态
      itemLineAudioTextChange: [], //每一项文案是否改变状态
      openMaterialModalType: "", //打开素材库弹窗类型  text:文案，video_image：视频音频
      AIWritingAssistantRef: null, //AI写作助手组件实例
    });

    // 回退
    const backClick = () => {
      endAudioPlay(); //结束音频播放
      router.go(-1);
    };

    // 初始化data数据
    onMounted(() => {
      store
        .dispatch("getRequestVoiceData")
        .then(() => {
          if (route.query.id) {
            getScriptLineDetail(); //接口请求数据
          } else {
            state.initData = createScriptData(); //初始化默认数据
            initializeData();
          }
        })
        .catch(() => {
          if (route.query.id) {
            getScriptLineDetail(); //接口请求数据
          } else {
            state.initData = createScriptData(); //初始化默认数据
            initializeData();
          }
        });
    });
    watch(
      () => route.query.id,
      (newValue, oldValue) => {
        if (newValue) {
          getScriptLineDetail(); //接口请求数据
          location.reload();
        }
      }
    );
    // 初始化列表数据
    const initializeData = () => {
      state.itemSpinning = Array(state.initData.script_scenes.length).fill(
        false
      );
      state.lineDubbingLoading = Array(
        state.initData.script_scenes.length
      ).fill(false);
      state.itemPlaying = Array(state.initData.script_scenes.length).fill(
        false
      );
      state.itemLineAudioTextChange = Array(
        state.initData.script_scenes.length
      ).fill(false);
    };
    // 控制AI写作助手按钮点击
    const isAIcanClick = computed(
      () =>
        state.itemSpinning.every((item) => !item) &&
        state.lineDubbingLoading.every((item) => !item)
    );
    /**
     * @description 获取脚本详情列表
     * @param {string} scriptLineId 脚本id
     * @returns {Promise}
     */
    const getScriptLineDetail = () => {
      request
        .get("/work_ai", "/user/shotstack/script-line/detail", {
          scriptLineId: route.query.id,
        })
        .then((res) => {
          state.initData = res.detail;
          state.initData.title = `${res.detail.title} 副本`;
          initializeData();
          console.log(state.initData, "初始化表格数据");
          console.log(res, "详情展示数据");
        });
    };
    // 单个台词配音组件
    const lineDubbing = ref(null);
    // 开启单个台词配音弹窗
    const lineAudioHandle = (info, index) => {
      endAudioPlay(); //结束音频播放
      state.parentIndex = index;
      // 打开设置弹窗
      lineDubbing.value.showModal(info, index);
    };
    // 关闭单个台词配音弹窗
    const closeDubbing = (info) => {
      const {
        audio_config: { open_global, ...audioConfigObj },
        isChange,
        line_audio,
        TextAreaChange,
        ...infoObj
      } = info;
      console.log(TextAreaChange, "是否改变");
      console.log(audioConfigObj, "9191919");
      // 开启了全局设置
      if (open_global) {
        // 更新全局台词配音设置
        state.initData.audio_config = audioConfigObj; //更新全局设置
        console.log(state.initData.audio_config, "更新全局音频设置");
        // 替换全部的音频设置
        state.initData.script_scenes = state.initData.script_scenes.map(
          (item) => {
            return {
              ...item,
              audio_config: {
                ...audioConfigObj, //替换音频设置
                open_global: item.audio_config.open_global, //是否开启全局不用全局替换
              },
            };
          }
        );
        state.initData.script_scenes[state.parentIndex].line_audio = line_audio; //更新单个台词文案
        state.initData.script_scenes[
          state.parentIndex
        ].audio_config.open_global = open_global; //自身的是否开启全局进行改变
        if (!isChange) {
          for (let i = 0; i < state.initData.script_scenes.length; i++) {
            state.initData.script_scenes[i].audio_detail = null; //清空混剪内生成的音频数据
            const {
              audio_config: { start_time, open_global, ...audioConfig },
              ...record
            } = state.initData.script_scenes[i];
            // 判断台词文案是否为空
            if (record.line_audio[0].elements[0][0].text.trim().length > 0) {
              // 有音频播放地址
              if (record.line_audio[0].audio_url.length > 0) {
                state.itemSpinning[i] = true; //开启播放按钮的加载
              } else {
                // 开启无音频地址的加载
                state.lineDubbingLoading[i] = true;
              }
              request
                .get("/work_ai", "/user/shotstack/textToVoice", {
                  ...audioConfig,
                  text: record.line_audio[0].elements[0][0].text,
                })
                .then((res) => {
                  let tiem = setInterval(() => {
                    request
                      .get("/work_ai", "/user/shotstack/getVoice", {
                        task_id: res.result.task_id,
                        request_id: res.result.request_id || "",
                      })
                      .then((task) => {
                        if (task.result.Data.ResultUrl) {
                          state.initData.script_scenes[i].line_audio[0] = {
                            ...state.initData.script_scenes[i].line_audio[0],
                            conver_to_audio: "on",
                            duration: task.result.duration,
                            duration_text: task.result.duration_text,
                            audio_url: task.result.Data.ResultUrl,
                            media_id: task.result.Data?.oss_media_id || "",
                          };
                          state.itemSpinning[i] = false;
                          state.lineDubbingLoading[i] = false;
                          clearInterval(tiem);
                        }
                      })
                      .catch((err) => {
                        state.itemSpinning[i] = false;
                        state.lineDubbingLoading[i] = false;
                        clearInterval(tiem);
                      });
                  }, 1000);
                });
            }
          }
        } else if (!TextAreaChange) {
          // 判断仅台词改变
          state.initData.script_scenes[state.parentIndex].audio_detail = null;
          const {
            audio_config: { start_time, open_global, ...audioConfig },
            ...record
          } = state.initData.script_scenes[state.parentIndex];
          // 判断台词文案是否为空
          if (record.line_audio[0].elements[0][0].text.trim().length > 0) {
            // 有音频播放地址
            if (record.line_audio[0].audio_url.length > 0) {
              state.itemSpinning[state.parentIndex] = true; //开启播放按钮的加载
            } else {
              // 开启无音频地址的加载
              state.lineDubbingLoading[state.parentIndex] = true;
            }
            request
              .get("/work_ai", "/user/shotstack/textToVoice", {
                ...audioConfig,
                text: record.line_audio[0].elements[0][0].text,
              })
              .then((res) => {
                let tiem = setInterval(() => {
                  request
                    .get("/work_ai", "/user/shotstack/getVoice", {
                      task_id: res.result.task_id,
                      request_id: res.result.request_id || "",
                    })
                    .then((task) => {
                      if (task.result.Data.ResultUrl) {
                        state.initData.script_scenes[
                          state.parentIndex
                        ].line_audio[0] = {
                          ...state.initData.script_scenes[state.parentIndex]
                            .line_audio[0],
                          conver_to_audio: "on",
                          duration: task.result.duration,
                          duration_text: task.result.duration_text,
                          audio_url: task.result.Data.ResultUrl,
                          media_id: task.result.Data?.oss_media_id || "",
                        };
                        state.itemSpinning[state.parentIndex] = false;
                        state.lineDubbingLoading[state.parentIndex] = false;
                        clearInterval(tiem);
                      }
                    })
                    .catch((err) => {
                      clearInterval(tiem);
                      state.itemSpinning[state.parentIndex] = false;
                      state.lineDubbingLoading[state.parentIndex] = false;
                    });
                }, 1000);
              })
              .catch((err) => {
                clearInterval(tiem);
                state.itemSpinning[state.parentIndex] = false;
                state.lineDubbingLoading[state.parentIndex] = false;
              });
          }
        } else {
          if (state.itemLineAudioTextChange[state.parentIndex]) {
            state.initData.script_scenes[state.parentIndex].audio_detail = null; //清空混剪内生成的音频数据
            const { start_time, ...audioConfig } = audioConfigObj;
            state.itemSpinning[state.parentIndex] = true;
            state.lineDubbingLoading[state.parentIndex] = true;
            request
              .get("/work_ai", "/user/shotstack/textToVoice", {
                ...audioConfig,
                text: state.initData.script_scenes[state.parentIndex]
                  .line_audio[0].elements[0][0].text,
              })
              .then((res) => {
                let tiem = setInterval(() => {
                  request
                    .get("/work_ai", "/user/shotstack/getVoice", {
                      task_id: res.result.task_id,
                      request_id: res.result.request_id || "",
                    })
                    .then((task) => {
                      if (task.result.Data.ResultUrl) {
                        state.initData.script_scenes[
                          state.parentIndex
                        ].line_audio[0] = {
                          ...state.initData.script_scenes[state.parentIndex]
                            .line_audio[0],
                          conver_to_audio: "on",
                          duration: task.result.duration,
                          duration_text: task.result.duration_text,
                          audio_url: task.result.Data.ResultUrl,
                          media_id: task.result.Data?.oss_media_id || "",
                        };
                        state.itemSpinning[state.parentIndex] = false;
                        state.lineDubbingLoading[state.parentIndex] = false;
                        state.itemLineAudioTextChange[
                          state.parentIndex
                        ] = false;
                        clearInterval(tiem);
                      }
                    })
                    .catch((err) => {
                      clearInterval(tiem);
                      state.itemSpinning[state.parentIndex] = false;
                      state.lineDubbingLoading[state.parentIndex] = false;
                      // state.itemLineAudioTextChange[state.parentIndex] = false;
                    });
                }, 1000);
              })
              .catch((err) => {
                clearInterval(tiem);
                state.itemSpinning[state.parentIndex] = false;
                state.lineDubbingLoading[state.parentIndex] = false;
              });
          }
        }
      } else {
        // 未开启全局设置,更新单个音频设置
        state.initData.script_scenes[state.parentIndex].audio_config =
          audioConfigObj;
        state.initData.script_scenes[state.parentIndex].line_audio = line_audio; //更新单个台词文案
        state.initData.script_scenes[
          state.parentIndex
        ].audio_config.open_global = open_global; //自身的是否开启全局进行改变
        if (!isChange || !TextAreaChange) {
          state.initData.script_scenes[state.parentIndex].audio_detail = null;
          const { start_time, ...audioConfig } = audioConfigObj;
          state.itemSpinning[state.parentIndex] = true;
          state.lineDubbingLoading[state.parentIndex] = true;
          request
            .get("/work_ai", "/user/shotstack/textToVoice", {
              ...audioConfig,
              text: state.initData.script_scenes[state.parentIndex]
                .line_audio[0].elements[0][0].text,
            })
            .then((res) => {
              let tiem = setInterval(() => {
                request
                  .get("/work_ai", "/user/shotstack/getVoice", {
                    task_id: res.result.task_id,
                    request_id: res.result.request_id || "",
                  })
                  .then((task) => {
                    if (task.result.Data.ResultUrl) {
                      state.initData.script_scenes[
                        state.parentIndex
                      ].line_audio[0] = {
                        ...state.initData.script_scenes[state.parentIndex]
                          .line_audio[0],
                        conver_to_audio: "on",
                        duration: task.result.duration,
                        duration_text: task.result.duration_text,
                        audio_url: task.result.Data.ResultUrl,
                        media_id: task.result.Data?.oss_media_id || "",
                      };
                      state.itemSpinning[state.parentIndex] = false;
                      state.lineDubbingLoading[state.parentIndex] = false;
                      clearInterval(tiem);
                    }
                  })
                  .catch((err) => {
                    state.itemSpinning[state.parentIndex] = false;
                    state.lineDubbingLoading[state.parentIndex] = false;
                    clearInterval(tiem);
                  });
              }, 1000);
            })
            .catch((err) => {
              state.itemSpinning[state.parentIndex] = false;
              state.lineDubbingLoading[state.parentIndex] = false;
              clearInterval(tiem);
            });
        } else {
          if (state.itemLineAudioTextChange[state.parentIndex]) {
            state.initData.script_scenes[state.parentIndex].audio_detail = null; //清空混剪内生成的音频数据
            const { start_time, ...audioConfig } = audioConfigObj;
            state.itemSpinning[state.parentIndex] = true;
            state.lineDubbingLoading[state.parentIndex] = true;
            request
              .get("/work_ai", "/user/shotstack/textToVoice", {
                ...audioConfig,
                text: state.initData.script_scenes[state.parentIndex]
                  .line_audio[0].elements[0][0].text,
              })
              .then((res) => {
                let tiem = setInterval(() => {
                  request
                    .get("/work_ai", "/user/shotstack/getVoice", {
                      task_id: res.result.task_id,
                      request_id: res.result.request_id || "",
                    })
                    .then((task) => {
                      if (task.result.Data.ResultUrl) {
                        state.initData.script_scenes[
                          state.parentIndex
                        ].line_audio[0] = {
                          ...state.initData.script_scenes[state.parentIndex]
                            .line_audio[0],
                          conver_to_audio: "on",
                          duration: task.result.duration,
                          duration_text: task.result.duration_text,
                          audio_url: task.result.Data.ResultUrl,
                          media_id: task.result.Data?.oss_media_id || "",
                        };
                        state.itemSpinning[state.parentIndex] = false;
                        state.lineDubbingLoading[state.parentIndex] = false;
                        state.itemLineAudioTextChange[
                          state.parentIndex
                        ] = false;
                        clearInterval(tiem);
                      }
                    })
                    .catch((err) => {
                      state.itemSpinning[state.parentIndex] = false;
                      state.lineDubbingLoading[state.parentIndex] = false;
                      // state.itemLineAudioTextChange[state.parentIndex] = false;
                      clearInterval(tiem);
                    });
                }, 1000);
              })
              .catch((err) => {
                state.itemSpinning[state.parentIndex] = false;
                state.lineDubbingLoading[state.parentIndex] = false;
                // state.itemLineAudioTextChange[state.parentIndex] = false;
              });
          }
        }
      }
    };
    // 子组件删除配音回调
    const deleteLineAudio = () => {
      isAudioConfigChange.value = false;
      state.itemLineAudioTextChange[state.parentIndex] = true;
      state.initData.script_scenes[state.parentIndex].line_audio[0] = {
        ...state.initData.script_scenes[state.parentIndex].line_audio[0],
        conver_to_audio: "off",
        duration: 0,
        audio_url: "",
      };
    };
    // 全局配音组件
    const globalLineDub = ref(null);
    let isAudioConfigChange = ref(false); //判断全局音频设置是否改变
    // 开启全局配音组件
    const globalAudioHandle = (info) => {
      endAudioPlay(); //结束音频播放
      // 打开设置弹窗
      globalLineDub.value.showModal(info);
    };
    // 关闭全局音频设置弹窗回调
    const closeglobalDubbing = (info) => {
      const { isChange, ...config } = info;
      console.log(config, "jjdjdj");
      isAudioConfigChange.value = isChange; //判断数据是否改变
      console.log(isChange, "数据是否改变");
      state.initData.audio_config = config; //设置全局
      // 循环单个音频设置更改配置项
      state.initData.script_scenes = state.initData.script_scenes.map(
        (item) => {
          return {
            ...item,
            audio_config: config,
          };
        }
      );
      // 如果数据改变了，针对已有的地址重新发送请求获取地址
      if (!isChange) {
        for (let i = 0; i < state.initData.script_scenes.length; i++) {
          state.initData.script_scenes[i].audio_detail = null; //清空台词音频
          const {
            audio_config: { start_time, open_global, ...audioConfig },
            ...record
          } = state.initData.script_scenes[i];
          // 判断台词文案是否为空
          if (record.line_audio[0].elements[0][0].text.trim().length > 0) {
            // 有音频播放地址
            if (record.line_audio[0].audio_url.length > 0) {
              state.itemSpinning[i] = true; //开启播放按钮的加载
            } else {
              // 开启无音频地址的加载
              state.lineDubbingLoading[i] = true;
            }
            request
              .get("/work_ai", "/user/shotstack/textToVoice", {
                ...audioConfig,
                text: record.line_audio[0].elements[0][0].text,
              })
              .then((res) => {
                let tiem = setInterval(() => {
                  request
                    .get("/work_ai", "/user/shotstack/getVoice", {
                      task_id: res.result.task_id,
                      request_id: res.result.request_id || "",
                    })
                    .then((task) => {
                      if (task.result.Data.ResultUrl) {
                        state.initData.script_scenes[i].line_audio[0] = {
                          ...state.initData.script_scenes[i].line_audio[0],
                          conver_to_audio: "on",
                          duration: task.result.duration,
                          duration_text: task.result.duration_text,
                          audio_url: task.result.Data.ResultUrl,
                          media_id: task.result.Data?.oss_media_id || "",
                        };
                        state.itemSpinning[i] = false;
                        state.lineDubbingLoading[i] = false;
                        clearInterval(tiem);
                      }
                    })
                    .catch((err) => {
                      state.itemSpinning[i] = false;
                      state.lineDubbingLoading[i] = false;
                      clearInterval(tiem);
                    });
                }, 1000);
              })
              .catch((err) => {
                state.itemSpinning[i] = false;
                state.lineDubbingLoading[i] = false;
              });
          }
        }
      } else {
        console.log(isChange);
        for (let i = 0; i < state.initData.script_scenes.length; i++) {
          if (state.itemLineAudioTextChange[i]) {
            state.initData.script_scenes[i].audio_detail = null; //清空混剪内生成的音频
            const {
              audio_config: { start_time, open_global, ...audioConfig },
              ...record
            } = state.initData.script_scenes[i];
            // 判断台词文案是否为空
            if (record.line_audio[0].elements[0][0].text.trim().length > 0) {
              // 有音频播放地址
              if (record.line_audio[0].audio_url.length > 0) {
                state.itemSpinning[i] = true; //开启播放按钮的加载
              } else {
                // 开启无音频地址的加载
                state.lineDubbingLoading[i] = true;
              }
              request
                .get("/work_ai", "/user/shotstack/textToVoice", {
                  ...audioConfig,
                  text: record.line_audio[0].elements[0][0].text,
                })
                .then((res) => {
                  let tiem = setInterval(() => {
                    request
                      .get("/work_ai", "/user/shotstack/getVoice", {
                        task_id: res.result.task_id,
                        request_id: res.result.request_id || "",
                      })
                      .then((task) => {
                        if (task.result.Data.ResultUrl) {
                          state.initData.script_scenes[i].line_audio[0] = {
                            ...state.initData.script_scenes[i].line_audio[0],
                            conver_to_audio: "on",
                            duration: task.result.duration,
                            duration_text: task.result.duration_text,
                            audio_url: task.result.Data.ResultUrl,
                            media_id: task.result.Data?.oss_media_id || "",
                          };
                          state.itemSpinning[i] = false;
                          state.lineDubbingLoading[i] = false;
                          state.itemLineAudioTextChange[i] = false;
                          clearInterval(tiem);
                        }
                      })
                      .catch((err) => {
                        state.itemSpinning[i] = false;
                        state.lineDubbingLoading[i] = false;
                      });
                  }, 1000);
                })
                .catch((err) => {
                  state.itemSpinning[i] = false;
                  state.lineDubbingLoading[i] = false;
                });
            }
          }
        }
      }
    };
    const scriptTitleOldValue = ref(""); //存储上次输入的模板标题值

    // 点击添加素材
    const importImg = (index, type) => {
      state.openMaterialModalType = "image_video";
      state.materiallibraryShow = true; //打开图片上传弹窗
      state.parentIndex = index; //父组件索引
      state.uploadType = type; //点击添加素材类型
      endAudioPlay(); //结束音频播放
    };
    // 导入台词文案
    let lineAudioIndex = ref(null);
    let copyLibraryModal = ref(null); //素材库导入组件实例
    // 文案库导入
    const openCopyLibraryModal = (index) => {
      state.openMaterialModalType = "text";
      copyLibraryModal.value && copyLibraryModal.value.showModal();
      lineAudioIndex.value = index;
      endAudioPlay(); //结束音频播放
    };
    // 导入文案成功回调
    const audioLItemImportSuccess = (info) => {
      if (info !== "") {
        state.initData.script_scenes[
          lineAudioIndex.value
        ].line_audio[0].elements[0][0].text = info[0].material_content;
        state.itemLineAudioTextChange[lineAudioIndex.value] = true;
        state.initData.script_scenes[lineAudioIndex.value].audio_detail = null; //清空混剪内生成的音频
      }
      copyLibraryModal.value && copyLibraryModal.value.closeModal();
    };
    // 素材选中回调
    const closeChooseMaterial = (info, key) => {
      if (!info) {
        return (state.materiallibraryShow = false); //关闭弹窗
      }
      state.materiallibraryShow = false; //关闭弹窗
      let filterList = info.map((item, index) => {
        return {
          // 文件路径
          material_url: item.material_url,
          // 文件名称
          material_name: item.material_name,
          // 素材类型
          scene_type: item.material_type,
          // id
          id: item.id,
          // 文件时长
          material_duration:
            item.material_type == "video" ? item.material_duration : 3000,
          end_time:
            item.material_type == "video" ? item.material_duration : 3000,
          // 文件后缀
          material_extension: item.material_extension,
          // 文件大小
          material_size: item.material_size,
          // 媒资id
          media_id: item?.oss_media_id || "",
        };
      });
      if (filterList.length < 1) {
        return;
      } else {
        filterList.forEach((item) => {
          // 分镜描述图片
          if (state.uploadType == "remark") {
            // 去重
            const indexId = state.initData.script_scenes[
              state.parentIndex
            ]?.remark_example_url.findIndex(
              (existingItem) => existingItem.id == item.id
            );
            if (indexId == -1) {
              state.initData.script_scenes[
                state.parentIndex
              ].remark_example_url.push({
                ...item,
              });
            }
          } else if (state.uploadType == "example_url") {
            // 已拍摄片段图片
            // 去重
            const indexId = state.initData.script_scenes[
              state.parentIndex
            ]?.example_url?.findIndex(
              (existingItem) => existingItem.id == item.id
            );

            if (indexId == -1) {
              state.initData.script_scenes[state.parentIndex].example_url.push({
                ...item,
              });
            }
          }
        });
      }
    };
    //  气泡子组件删除图片回调
    const deleteParentUrl = (info) => {
      if (info.updateType == "remark_example_url") {
        const indexKey = state.initData.script_scenes[
          info.parentIndex
        ].remark_example_url?.findIndex(
          (extendsItem) => extendsItem.id == info.id
        );
        state.initData.script_scenes[
          info.parentIndex
        ].remark_example_url.splice(indexKey, 1);
      } else if (info.updateType == "example_url") {
        const indexKey = state.initData.script_scenes[
          info.parentIndex
        ].example_url?.findIndex((extendsItem) => extendsItem.id == info.id);
        console.log(indexKey);
        state.initData.script_scenes[info.parentIndex].example_url.splice(
          indexKey,
          1
        );
      }
    };
    // 气泡子组件新增图片回调
    const updateParentsUrl = (info) => {
      if (info.updateType == "remark_example_url") {
        let maxRemarkExampleUrlCount =
          info.filterList.length +
          state.initData.script_scenes[info.parentIndex].remark_example_url
            .length;
        if (maxRemarkExampleUrlCount > 50) {
          return message.error("单个镜头最多只能导入50个分镜描述");
        }
        info.filterList.forEach((item) => {
          const index = state.initData.script_scenes[
            info.parentIndex
          ].remark_example_url?.findIndex(
            (existingItem) => existingItem.id == item.id
          );
          if (index == -1) {
            state.initData.script_scenes[
              info.parentIndex
            ].remark_example_url.push({
              ...item,
            });
          }
        });
      } else if (info.updateType == "example_url") {
        let maxExampleUrlCount =
          info.filterList.length +
          state.initData.script_scenes[info.parentIndex].example_url.length;
        if (maxExampleUrlCount > 50) {
          return message.error("单个镜头最多只能导入50个拍摄片段");
        }
        info.filterList.forEach((item) => {
          const index = state.initData.script_scenes[
            info.parentIndex
          ].example_url?.findIndex(
            (existingItem) => existingItem.id == item.id
          );
          if (index == -1) {
            state.initData.script_scenes[info.parentIndex].example_url.push({
              ...item,
            });
          }
        });
      }
    };
    // 保存脚本
    const handleSaveScript = (submitType) => {
      endAudioPlay(); //结束音频播放
      // 判断脚本名称不能为空
      if (state.initData.title.trim().length < 1) {
        message.error("脚本名称不能为空");
        return;
      }
      // 判断分镜头名称不能为空
      let flag = false;
      state.initData.script_scenes.forEach((item, index) => {
        if (item.name.trim().length < 1) {
          console.log(item.name, "分镜名称");
          flag = true;
          return;
        }
      });
      if (flag) {
        message.error("分镜标题不能为空");
        return;
      }
      // 编辑
      if (route.query.id) {
        request
          .put("/work_ai", "/user/shotstack/script-line/update", {
            ...state.initData,
            id: route.query.id,
          })
          .then((res) => {
            if (res) {
              // 判断当前是否是保存或者编辑
              if (submitType == "save") {
                router.push({
                  name: "ScriptingTool",
                });
              } else if (submitType == "mixcut") {
                router.push({
                  name: "mixedCutCreat",
                  query: { mixcutId: res.result, type: 0, viewType: 2 },
                });
              }
            }
          })
          .finally(() => {});
      } else {
        // 添加
        request
          .post("/work_ai", "/user/shotstack/script-line/add", state.initData)
          .then((res) => {
            if (res) {
              if (submitType == "save") {
                router.push({
                  name: "ScriptingTool",
                });
              } else if (submitType == "mixcut") {
                router.push({
                  name: "mixedCutCreat",
                  query: { mixcutId: res.result, type: 0, viewType: 2 },
                });
              }
            }
          })
          .finally(() => {});
      }
    };
    // 添加一行
    const addHandle = () => {
      if (state.initData.script_scenes.length >= 10) {
        return message.error("最多可以添加十个分镜");
      } else {
        const newItem = baseScriptScenesItem(); // 创建新的数据项
        state.initData.script_scenes.push(newItem); // 将新数据项添加到 state.initData.script_scenes 中
        state.itemSpinning = Array(state.initData.script_scenes.length).fill(
          false
        );
        state.lineDubbingLoading =
          state.initData &&
          Array(state.initData.script_scenes.length).fill(false);
        state.itemPlaying = Array(state.initData.script_scenes.length).fill(
          false
        );
        state.itemLineAudioTextChange = Array(
          state.initData.script_scenes.length
        ).fill(false);
      }
    };

    // 台词文案文本框失焦事件
    const lineAudioBlurHandle = (index) => {
      // 如果文本被清空了,就清除音频
      if (
        state.initData.script_scenes[index].line_audio[0].elements[0][0].text ==
        ""
      ) {
        state.initData.script_scenes[index].line_audio[0] = {
          ...state.initData.script_scenes[index].line_audio[0],
          conver_to_audio: "off",
          audio_url: "",
        };
      } else {
      }
    };
    let currentAudio = ref(null); //记录当前播放的音频实例
    // 播放音频
    const playAudio = (item, index) => {
      state.parentIndex = index;
      if (state.itemLineAudioTextChange[index]) {
        const { start_time, ...audioConfig } =
          state.initData.script_scenes[index];
        state.itemSpinning[state.parentIndex] = true;
        state.lineDubbingLoading[state.parentIndex] = true;
        request
          .get("/work_ai", "/user/shotstack/textToVoice", {
            ...audioConfig,
            text: state.initData.script_scenes[index].line_audio[0]
              .elements[0][0].text,
          })
          .then((res) => {
            let tiem = setInterval(() => {
              request
                .get("/work_ai", "/user/shotstack/getVoice", {
                  task_id: res.result.task_id,
                  request_id: res.result.request_id || "",
                })
                .then((task) => {
                  if (task.result.Data.ResultUrl) {
                    state.initData.script_scenes[
                      state.parentIndex
                    ].line_audio[0] = {
                      ...state.initData.script_scenes[index].line_audio[0],
                      conver_to_audio: "on",
                      duration: task.result.duration,
                      duration_text: task.result.duration_text,
                      audio_url: task.result.Data.ResultUrl,
                      media_id: task.result.Data?.oss_media_id || "",
                    };
                    state.itemSpinning[index] = false;
                    state.lineDubbingLoading[index] = false;
                    state.itemLineAudioTextChange[index] = false;
                    clearInterval(tiem);
                  }
                })
                .catch((err) => {
                  state.itemSpinning[index] = false;
                  state.lineDubbingLoading[index] = false;
                });
            }, 1000);
          })
          .catch((err) => {
            state.itemSpinning[index] = false;
            state.lineDubbingLoading[index] = false;
          });
        return;
      }
      const audioPlayer = document.getElementById(`audio-${item.id}`);
      // 播放相同音频地址
      if (audioPlayer === currentAudio.value) {
        audioPlayer.play();
        state.itemPlaying[index] = true;
      } else {
        // 播放不同地址
        if (currentAudio.value) {
          currentAudio.value.pause();
          currentAudio.value.currentTime = 0;
        }
        audioPlayer.play();
        currentAudio.value = audioPlayer;
        state.itemPlaying = state.itemPlaying.map((item, i) =>
          i === index ? true : false
        );
      }
    };
    // 暂停播放
    const pauseAudio = (record, index) => {
      state.parentIndex = index;
      if (currentAudio.value) {
        currentAudio.value.pause();
        state.itemPlaying = state.itemPlaying.map(() => false);
        state.itemLineAudioTextChange[index] = false;
      }
    };
    // 音频播放结束回调
    const endAudioPlay = (record, index) => {
      // state.parentIndex = index;
      if (currentAudio.value) {
        currentAudio.value.pause();
        currentAudio.value.currentTime = 0;
        state.itemPlaying = state.itemPlaying.map(() => false);
        state.itemLineAudioTextChange[index] = false;
      }
    };
    const lineAudioChangeHandle = (index) => {
      state.parentIndex = index;
      // console.log(state.itemLineAudioTextChange, "002020");
      state.itemLineAudioTextChange[index] = true;
      state.initData.script_scenes[index].audio_detail = null; //清空混剪内生成的音频
    };
    // 删除行
    const deleteLineHandle = (index) => {
      if (state.initData.script_scenes.length <= 3) {
        return message.error("分镜数量不能少于3个");
      } else {
        state.initData.script_scenes.splice(index, 1);
        initializeData();
      }
    };
    // 删除整行内容
    const deleteContentHandle = (index) => {
      const newItem = baseScriptScenesItem();
      state.initData.script_scenes[index] = newItem;
    };
    // 向上添加一行
    const addLineTopHandle = (index) => {
      console.log("向上添加");
      if (state.initData.script_scenes.length >= 10) {
        return message.error("最多可以添加十个分镜");
      } else {
        const newItem = baseScriptScenesItem();
        state.initData.script_scenes.splice(index - 1, 0, newItem);
        initializeData();
      }
    };
    // 向下添加一行
    const addLineBottomHandle = (index) => {
      console.log("向下添加");
      if (state.initData.script_scenes.length >= 10) {
        return message.error("最多可以添加十个分镜");
      } else {
        const newItem = baseScriptScenesItem();
        state.initData.script_scenes.splice(index + 1, 0, newItem);
        initializeData();
      }
    };
    //   创建副本
    const handleSaveScriptCopy = () => {
      if (state.initData.title.trim().length < 1) {
        // 判断模板内容不能为空
        message.error("脚本名称不能为空");
        return;
      }
      // 判断分镜头名称不能为空
      let flag = false;
      state.initData.script_scenes.forEach((item, index) => {
        if (item.name.trim().length < 1) {
          console.log(item.name, "分镜名称");
          flag = true;
          return;
        }
      });
      if (flag) {
        message.error("分镜标题不能为空");
        return;
      }
      const { id, ...params } = state.initData;
      request
        .post("/work_ai", "/user/shotstack/script-line/add", params)
        .then((res) => {
          if (res) {
            router.replace({
              path: "/templateScriptCopy",
              query: {
                id: res.result,
              },
            });
          }
        })
        .finally(() => {});
    };
    // 风险词检测
    const riskWordDetection = ref(null);
    const riskWordDetnHandle = (data, index) => {
      const isImpty = data?.script_scenes?.some(
        (item) => item.line_audio[0].elements[0][0].text.trim().length > 0
      );
      console.log(isImpty);
      if (isImpty) {
        let text_arr = data.script_scenes.map((item) => {
          return item.line_audio[0].elements[0][0].text;
        });
        riskWordDetection.value &&
          riskWordDetection.value.showDrawer(text_arr, "script_scenes");
      } else {
        message.warning("请输入台词文案");
      }
    };
    // AI写作助手导入
    const AIWritingAssistantHandle = () => {
      endAudioPlay();
      state.AIWritingAssistantRef.showDrawer();
    };
    // AI写作助手成功回调
    const emitArr = (arr) => {
      if (arr && arr.length) {
        arr.forEach((item, index) => {
          if (index < state.initData.script_scenes.length) {
            // 替换代码
            state.initData.script_scenes[index].name = item.title; // 替换文本
            state.initData.script_scenes[
              index
            ].line_audio[0].elements[0][0].text =
              splitTextAndRemoveCommas(
                item?.subtitle_text_block?.map((ele) => ele.text)?.join(",")
              )?.join("\n") || "";
          } else {
            // 追加代码
            const baseItem = baseScriptScenesItem();
            baseItem.name = item.title;
            baseItem.line_audio[0].elements[0][0].text =
              splitTextAndRemoveCommas(
                item?.subtitle_text_block?.map((ele) => ele.text)?.join(",")
              )?.join("\n") || "";
            state.initData.script_scenes.push(baseItem);
          }
        });
        initializeData(); //初始化
        arr.forEach((item, index) => {
          state.itemLineAudioTextChange[index] = true; //文案变化了标识
          state.initData.script_scenes[index].audio_detail = null; //清空混剪内生成的音频
        });
      }
      state.AIWritingAssistantRef.closeDrawer();
    };
    return {
      ...toRefs(state),
      backClick,
      getScriptLineDetail,
      scriptTitleOldValue,
      lineAudioHandle,
      lineDubbing,
      importImg,
      closeChooseMaterial,
      deleteParentUrl,
      handleSaveScript,
      addHandle,
      globalLineDub,
      globalAudioHandle,
      closeglobalDubbing,
      closeDubbing,
      initializeData,
      updateParentsUrl,
      isAudioConfigChange,
      deleteLineAudio,
      lineAudioBlurHandle,
      playAudio,
      pauseAudio,
      currentAudio,
      endAudioPlay,
      lineAudioChangeHandle,
      deleteLineHandle,
      deleteContentHandle,
      addLineTopHandle,
      addLineBottomHandle,
      handleSaveScriptCopy,
      riskWordDetnHandle,
      riskWordDetection,
      lineAudioIndex,
      copyLibraryModal,
      openCopyLibraryModal,
      audioLItemImportSuccess,
      isAIcanClick,
      AIWritingAssistantHandle,
      emitArr,
    };
  },
});
</script>

<style lang="less" scoped>
.container {
  width: 100%;

  // overflow: hidden;
  .content-page {
    padding: 40px 30px;

    // 头部输入框
    .top-ipt {
      height: 60px;
      margin-bottom: 30px;
      display: flex;
      align-items: center;
      width: 100%;

      .ipt {
        width: 100%;
        border: none;
        height: 100%;
        display: flex;
        align-items: center;
        padding: 5px;

        /* 添加内边距 */
        .ant-input {
          width: 100%;
          font-size: 20px;
          /* 自定义的字体大小 */
        }
      }
    }

    // 列表------
    // 删除按钮
    .delet-btn {
      width: 20px;
      height: 20px;
      font-size: 15px;
      background: #f6f8fa;
    }

    // 台词文案头部样式
    .th_line_audio {
      display: flex;
      height: 100%;
      padding: 0 20px;
      justify-content: space-between;
    }

    // 台词文案头部样式

    // 分镜名称
    .td_storyboard_name {
      display: flex;
      width: 100%;
      flex-direction: column;
      height: 180px;

      .font-count {
        text-align: right;
        color: #c5c5d4;
      }
    }

    // 分镜描述
    .td_storyboard_desc {
      display: flex;
      height: 180px;

      .td_storyboard_descLf {
        display: flex;
        flex: 1;
        flex-direction: column;
        margin-right: 30px;

        .font-count {
          text-align: right;
          color: #c5c5d4;
        }
      }
    }

    // 台词文案
    .td_line_audio {
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 180px;
      justify-content: space-between;

      .line_dubbing-textarea {
        flex: 1;
      }

      // 无音频 播放地址
      .line_dubbing {
        width: 100%;
        padding: 10px;
        display: flex;
        align-items: center;

        .line_dubbing_btn {
          border: 1px solid #eaedf1;
          display: flex;
          align-items: center;
          padding: 2px 5px;
          cursor: pointer;
        }

        .import_material {
          opacity: 0;
          transition: all 0.3s;
        }
      }

      // 有音频播放地址
      .hasurl_line_dubbing {
        width: 100%;
        padding: 10px;
        display: flex;
        align-items: center;

        .line_dubbing_btn {
          border: 1px solid #eaedf1;
          display: flex;
          align-items: center;
          padding: 2px 5px;
          cursor: pointer;
        }

        .import_material {
          opacity: 0;
          transition: all 0.3s;
        }
      }

      &:hover .import_material {
        opacity: 1;
      }
    }

    // 禁用输入框拖拽功能
    .no-resize {
      resize: none;
    }

    // 图片
    .file-upload-img {
      // 新增图片--无图片情况
      cursor: pointer;
      display: flex;
      justify-content: center;

      .upload-img {
        background: #f6f8fa;
        height: 160px;
        width: 125px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: #c7ccd6;
        border: 1px dotted #dde2e9;

        &:hover {
          background: #f1f3f5;
        }
      }

      // 列表展示--有图片情况
      .file-img {
        height: 180px;
        width: 140px;
        background: black;
        position: relative;

        // 图片数量
        .img-count {
          position: absolute;
          width: 30px;
          height: 30px;
          line-height: 30px;
          text-align: center;
          border-radius: 3px;
          background: #201f20;
          color: #fff;
          right: 0;
          bottom: 0;
        }
      }
    }

    // 列表------
    .addLine {
      widows: 100%;
      display: flex;
      justify-content: center;
      font-weight: 500;
      cursor: pointer;

      span {
        width: 130px;
        height: 35px;
        text-align: center;
        line-height: 30px;
        border: 1px solid #f2f4f6;
        background: #fafbfc;
        border-bottom-left-radius: 20px;
        border-bottom-right-radius: 20px;
        position: relative;
      }
    }
  }

  .btn {
    display: flex;
    align-items: center;
    // background: skyblue;
  }
}

:deep(.ant-table-body) {
  max-height: 600px;
  overflow-y: auto;

  &::-webkit-scrollbar {
    width: 6px;
    background: #fafafa;
  }

  &::-webkit-scrollbar-track {
    width: 5px;
    background-color: transparent;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: rgba(193, 193, 193, 0.5);
    background-clip: padding-box;
    min-height: 28px;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
  }
}

.textarea {
  &::-webkit-scrollbar {
    display: none;
  }

  &::-webkit-scrollbar-track {
    width: 5px;
    background-color: transparent;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: rgba(193, 193, 193, 0.5);
    background-clip: padding-box;
    min-height: 28px;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
  }
}
</style>
